package org.wx.herostory.services.encoder;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.wx.herostory.model.MoveState;
import org.wx.herostory.msg.GameMsgProtocol;
import org.wx.herostory.model.User;
import org.wx.herostory.services.util.Broadcaster;
import org.wx.herostory.services.util.UserManager;

/**
 * @program: my-java
 * @description: 场上现在还有谁
 * @author: Wang.xun
 * @create: 2021-03-01 21:43
 **/
@Slf4j
public class WhoElseIsHereCmdHandler implements ICmdHandler<GameMsgProtocol.WhoElseIsHereCmd>{
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.WhoElseIsHereCmd cmd) {
        if(null == ctx || null == cmd){
            return;
        }
        log.info("询问还有谁在线");

        GameMsgProtocol.WhoElseIsHereResult.Builder resultBuilder = GameMsgProtocol.WhoElseIsHereResult.newBuilder();
        // 取出所有在线用户
        for (User currUser : UserManager.listUsers()) {

            GameMsgProtocol.WhoElseIsHereResult.UserInfo.Builder
                    userInfoBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.newBuilder();
            userInfoBuilder.setUserId(currUser.userId);
            userInfoBuilder.setUserName(currUser.userName);
            userInfoBuilder.setHeroAvatar(currUser.heroAvatar);

            // 构建移动状态
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.Builder
                    mvStateBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.newBuilder();
            mvStateBuilder.setFromPosX(currUser.moveState.fromPosX);
            mvStateBuilder.setFromPosY(currUser.moveState.fromPosY);
            mvStateBuilder.setToPosX(currUser.moveState.toPosX);
            mvStateBuilder.setToPosY(currUser.moveState.toPosY);
            mvStateBuilder.setStartTime(currUser.moveState.startTime);
            userInfoBuilder.setMoveState(mvStateBuilder);

            resultBuilder.addUserInfo(userInfoBuilder);
        }

        GameMsgProtocol.WhoElseIsHereResult whoElseIsHereResult = resultBuilder.build();
        // 谁问给谁返回
        ctx.writeAndFlush(whoElseIsHereResult);


    }
}
